package org.dreamwork.jasmine2.engine;

import org.dreamwork.i18n.IResourceManager;
import org.dreamwork.jasmine2.configure.JasmineConfig;
import org.dreamwork.jasmine2.i18n.IWebResourceManagerFactory;
import org.dreamwork.jasmine2.restful.APIDefinition;
import org.dreamwork.jasmine2.restful.RestfulAPIManager;
import org.dreamwork.util.StringUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: seth.yang
 * Date: 12-10-22
 * Time: 下午2:48
 *
 * todo: 合并所有的已知的启动项
 */
public class JasmineContextListener implements ServletContextListener {
    public void contextInitialized (ServletContextEvent event) {
        ServletContext context = event.getServletContext ();
        String configFile = context.getInitParameter (JasmineConfig.JASMINE_CONFIG_FILE);
        if (StringUtil.isEmpty (configFile))
            configFile = "/WEB-INF/jasmine.xml";
//            throw new RuntimeException ("Can't find jasmine config");

        try {
            URL url = context.getResource (configFile);
            if (url != null) {
                JasmineConfig.parse (url);
            } else {
                File file = new File (configFile);
                if (file.exists () && file.canRead ()) {
                    JasmineConfig.parse (file.toURI().toURL ());
                } else {
                    throw new RuntimeException ("Jasmine config file " + configFile + " can't open");
                }
            }

            if (JasmineConfig.i18n != null)
                initI18n (context);

            if (JasmineConfig.apiDefinitionMap != null) {
                context.setAttribute (RestfulAPIManager.KEY_API_MAPPING, JasmineConfig.apiDefinitionMap);
            } else if (JasmineConfig.restfulApiConfigURL != null) {
                InputStream in = context.getResourceAsStream (JasmineConfig.restfulApiConfigURL);
                if (in != null) {
                    Map<String, APIDefinition> map = RestfulAPIManager.load (in, context);
                    context.setAttribute (RestfulAPIManager.KEY_API_MAPPING, map);
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException (ex);
        }
    }

    public void contextDestroyed (ServletContextEvent servletContextEvent)  {
    }

    @SuppressWarnings ("unchecked")
    private void initI18n (ServletContext context) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        String resourceBase = JasmineConfig.i18n.resource;
        HttpContext hc = new HttpContext ();
        hc.setApplication (context);
        Class<IWebResourceManagerFactory> c = (Class<IWebResourceManagerFactory>) Class.forName (JasmineConfig.i18n.resourceManager);
        IWebResourceManagerFactory factory = c.newInstance ();
        IResourceManager manager = factory.getResourceManager (context, JasmineConfig.i18n.defaultLocale, resourceBase);

        context.setAttribute (JasmineConfig.JASMINE_I18N_HOLDER, manager);
        context.setAttribute (JasmineConfig.SUPPORTED_LOCALES, manager.getSupportedLocales ());
        context.setAttribute (JasmineConfig.DEFAULT_LOCALE, JasmineConfig.i18n.defaultLocale);
    }
}